﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using UnityEngine;

namespace State
{
    /// <summary>
    /// 某组状态的抽象基类
    /// </summary>
    public abstract class StateBase : MonoBehaviour, IState<StateBase>
    {
        /// <summary>
        /// 拥有状态的对象
        /// </summary>
        public BaseContextBase Context;
        /// <summary>
        /// 从某状态切换过来的时候
        /// </summary>
        /// <typeparam name="T">来自哪一个状态</typeparam>
        public virtual void OnStateEnter(StateBase perviousState)
        {
            Debug.Log(string.Format("{0} ---> {1}", GetType().Name, perviousState.GetType().Name));
        }

        /// <summary>
        /// 离开本状态切换至下一个状态的时候
        /// </summary>
        /// <typeparam name="T">下一个是什么状态</typeparam>
        public virtual void OnStateExit(StateBase nextState)
        {
        }

        public virtual bool Try2ChangeState<T>() where T : StateBase
        {
            Change2State<T>();
            return true;
        }

        protected virtual void Change2State<T>() where T : StateBase
        {
            T nextState = Context.transform.GetComponentInChildren<T>();
            if(nextState == null)
            {
                GameObject go = new GameObject(typeof(T).Name);
                nextState = go.AddComponent<T>();
                nextState.Context = Context;
                go.transform.parent = transform.parent;
            }

            OnStateExit(nextState);
            nextState.OnStateEnter(this);
        }
        protected virtual void Change2State(StateBase nextState)
        {
            OnStateExit(nextState);
            nextState.OnStateEnter(this);
        }
    }
}
